<template>
  <div class="app-container h-flex">
    <div class="app-container__left tree-box">
      <div class="type-title">业务类型</div>
      <ul class="type-list">
        <li
          :class="{ active: listQuery.errorType === '' }"
          @click="chooseErrorType('')">所有类型</li>
        <li
          v-for="item in errorTypeList"
          :key="item.type"
          :class="{ active: item.type === listQuery.errorType }"
          @click="chooseErrorType(item.type)">{{ item.name }}</li>
      </ul>
    </div>
    <div ref="container" class="app-container__right h-flex-elastic v-flex overflow-hidden">
      <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
      <div ref="main" class="v-flex-elastic">
        <base-table
          :height="height"
          :loading="listLoading"
          :data="tableData"
          :columns="columns"
          :default-operations="defaultOperations"
          show-filter-column
          operaton-width="130px"
          @view="view"
          @updateForm="updateForm"
          @deleteData="deleteData">
          <span slot="original" slot-scope="{row}" style="cursor: pointer;" @click="showJson(row)">
            {{ row.original }}
          </span>
          <template slot="ruleList" slot-scope="{row}">
            <el-tag
              v-for="(rule, index) in row.ruleList"
              :key="index"
              size="normal">
              {{ rule }}
            </el-tag>
          </template>
        </base-table>
      </div>
      <div class="page-box">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :size.sync="listQuery.size"
          @pagination="getListPage" />
      </div>
    </div>
    <base-dialog
      class="pretreatment-rule-dialog"
      width="86%"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @close="beforeCloseDialog"
      @updateData="updateData">
      <el-form
        ref="dataForm"
        :rules="dialog.rules"
        :model="dialog.form"
        :disabled="dialog.disabled"
        label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="规则类型" prop="type">
              <el-select v-model="dialog.form.type" :disabled="!!dialog.form.id" @change="changeType">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预处理类型" prop="errorType">
              <el-select v-model="dialog.form.errorType" @change="changeErrorType">
                <el-option
                  v-for="(item, index) in errorTypeList"
                  :key="index"
                  :value="item.type"
                  :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="(dialog.form.type === 0 || dialog.form.type === 1)"
              label="修正值"
              prop="data"
              :rules="currentErrorType.rules || defaultRules">
              <template v-if="currentErrorType.chooseType === 'selectTree'">
                <select-tree
                  v-model="dialog.form.data.deptId"
                  node-click
                  :options="selectData"
                  :props="{ label: 'label', value: 'id', parent: 'parentId', children: 'children' }"
                  @nodeClick="changeDept"
                  @clear="clearDept" />
              </template>
              <template v-else-if="currentErrorType.chooseType === 'selectTable'">
                <select-table
                  ref="selectTable"
                  v-model="dialog.form.data[currentErrorType.key]"
                  :filter-form="currentErrorType.filterForm"
                  :filter-data="currentErrorType.filterData"
                  :default-data="selectData"
                  :columns="currentErrorType.columns"
                  :total="currentErrorType.total"
                  :filter-fn="currentErrorType.interface"
                  @current-change="changeData"
                  @clear="dialog.form.data={}" />
              </template>
              <template v-else-if="currentErrorType.chooseType === 'select'">
                <el-select v-model="dialog.form.data" clearable @change="changeSelect">
                  <el-option
                    v-for="(item, index) in currentErrorType.list"
                    :key="index"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </template>
            </el-form-item>
            <el-form-item
              v-else-if="dialog.form.type === 2"
              label="修正值"
              prop="data"
              :rules="defaultRules1">
              <el-input v-model="dialog.form.data" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dialog.form.type === 0" label="错误编码" prop="errorCode">
              <el-input key="1" v-model="dialog.form.errorCode" clearable />
            </el-form-item>
            <el-form-item
              v-else-if="dialog.form.type === 1 || dialog.form.type === 2"
              :label="dialog.form.type === 1 ? '别名' : '替换规则'"
              prop="ruleList">
              <div class="rule-tags">
                <el-tag
                  v-for="(rule, index) in dialog.form.ruleList"
                  :key="index"
                  size="normal"
                  closable
                  @close="handleCloseRule(index)">
                  {{ rule }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  key="2"
                  ref="ruleInput"
                  v-model="inputValue"
                  class="rule-tag-input"
                  size="small"
                  @keyup.enter.native="handleRuleInputConfirm"
                  @blur="handleRuleInputConfirm" />
                <el-button v-else class="rule-tag-button" size="small" @click="showRuleInput">+ 新规则</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <base-dialog
      class="pretreatment-rule-dialog1"
      :visible.sync="dialog1.visible"
      :title="dialog1.title"
      :show-default-footer="false">
      <div class="json-viewer-container">
        <json-viewer
          :value="viewJson"
          :expand-depth="5"
          copyable
          sort />
      </div>
    </base-dialog>
  </div>
</template>
<script>
import {
  getListPage,
  updateData,
  deleteData
} from '@/api/cms/pretreatment/pretreatment-rule'
import { getErrorType } from '@/api/cms/pretreatment/pretreatment-data'
import { getListTree as devClassList } from '@/api/dsc/equipment-resume/species'
import { getListAllTree as departmentList } from '@/api/dsc/system/department'
import { getListPage as lineList, lineList as lineTreeList } from '@/api/dsc/location-area-info/line'
import { getListPage as siteList, getListByLineId } from '@/api/dsc/location-area-info/site'
import { getListPage as directionList } from '@/api/dsc/location-area-info/direction-diff'
import { getListPage as trackList } from '@/api/dsc/location-area-info/track'
import { getListPage as tunnelList } from '@/api/dsc/location-area-info/tunnel'
import { getListPage as anchorList } from '@/api/dsc/location-area-info/anchor'
import { getListPage as pillarList } from '@/api/dsc/equipment-resume/pillar'
import { getListPage as deviceList } from '@/api/dsc/equipment-resume/device'
import { getListPage as device6cList } from '@/api/dsc/equipment-resume/6c-device'
import { getListPage as userDefectTypeList } from '@/api/dsc/problem/user-defect-type'
import { getListPage as userDefectGradeList } from '@/api/dsc/problem/user-defect-level'
import { isEmptyObject } from '@/utils'
import JsonViewer from 'vue-json-viewer'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscPretreatmentRule',
  components: { JsonViewer },
  mixins: [tableMixin],
  data() {
    return {
      listQuery: {
        page: 1,
        size: 20
      },
      filterData: {
        type: {
          key: 'type',
          type: 'select',
          title: '规则类型',
          placeholder: '所有规则类型',
          options: []
        },
        errorType: {
          key: 'errorType',
          type: 'select',
          title: '预处理类型',
          placeholder: '所有预处理类型',
          options: []
        }
      },
      height: 0,
      listLoading: true,
      tableData: [],
      defaultOperations: ['view', 'edit', 'delete'],
      columns: [
        { label: '规则类型', prop: 'type', formatter: row => this.types.filter(item => item.value === row.type)[0].label },
        { label: '预处理类型', prop: 'errorType', formatter: row => this.errorTypeList.filter(item => item.type === row.errorType)[0].name },
        { label: '错误编码', prop: 'errorCode' },
        { label: '别名/替换规则', prop: 'ruleList', template: true },
        {
          label: '修正值',
          prop: 'modify',
          formatter: row => {
            const type = this.errorTypes[row.errorType]
            if (type.chooseType === 'select') {
              return type.list.filter(item => item.value === row.data)[0].label
            } else {
              return row.data[type.key]
            }
          }
        },
        { label: '修前值', prop: 'original', template: true }
      ],
      total: 0,
      dialog: {
        title: '',
        visible: false,
        disabled: false,
        loading: false,
        form: {},
        rules: {
          type: { required: true, message: '请选择', trigger: 'change' },
          errorType: { required: true, message: '请选择', trigger: 'change' },
          errorCode: { required: true, message: '请输入', trigger: 'blur' },
          ruleList: { type: 'array', required: true, message: '请添加', trigger: 'change' }
        }
      },
      inputVisible: false,
      inputValue: '',
      currentRow: [],
      types: [
        { label: '编码预处理', value: 0 },
        { label: '别名', value: 1 },
        { label: '替换', value: 2 }
      ],
      errorTypeList: [],
      errorTypes: {
        DEPT: {
          chooseType: 'selectTree',
          type: 'DEPT',
          key: 'deptName',
          name: '部门',
          interface: departmentList,
          list: [],
          data: {
            deptId: 'deptId',
            deptCode: 'deptCode',
            deptName: 'deptName',
            parentCode: 'parentCode'
          }
        },
        LINE: {
          chooseType: 'selectTable',
          type: 'LINE',
          key: 'lineName',
          name: '线路',
          interface: lineList,
          list: [],
          data: {
            lineId: 'id',
            lineCode: 'lineCode',
            lineName: 'lineName'
          },
          filterForm: {
            lineName: '',
            page: 1,
            size: 20
          },
          filterData: {
            lineName: {
              key: 'lineName',
              type: 'input',
              placeholder: '线路'
            }
          },
          columns: [
            { property: 'lineName', label: '线路' },
            { label: '铁路类别', property: 'railTypeText' },
            { label: '线路等级', property: 'lineLevelText' },
            { label: '线路类型', property: 'lineTypeText' }
          ],
          total: 0
        },
        LINE_SITE: {
          chooseType: 'selectTable',
          type: 'LINE_SITE',
          key: 'siteName',
          name: '区间站场',
          interface: siteList,
          list: [],
          data: {
            siteId: 'id',
            // siteId: 'siteId',
            lineSiteCode: 'lineSiteCode',
            siteName: 'siteName',
            lineId: 'lineId'
          },
          filterForm: {
            siteName: '',
            page: 1,
            size: 20
          },
          filterData: {
            siteName: {
              key: 'siteName',
              type: 'input',
              placeholder: '区间站场'
            }
          },
          columns: [
            { property: 'siteName', label: '区间站场' },
            { property: 'siteTypeName', label: '区站类型' },
            { property: 'lineName', label: '所属线路' },
            { property: 'directionName', label: '行别' }
          ],
          total: 0
        },
        DIRECTION: {
          chooseType: 'selectTable',
          type: 'DIRECTION',
          key: 'directionName',
          name: '行别',
          interface: directionList,
          list: [],
          data: {
            directionId: 'id',
            directionCode: 'directionCode',
            directionName: 'directionName'
          },
          filterForm: {
            keyName: '',
            page: 1,
            size: 20
          },
          filterData: {
            keyName: {
              key: 'keyName',
              type: 'input',
              placeholder: '行别名称、编号、备注'
            }
          },
          columns: [
            { property: 'directionName', label: '行别' }
          ],
          total: 0
        },
        TRACK: {
          chooseType: 'selectTable',
          type: 'TRACK',
          key: 'trackName',
          name: '股道',
          interface: trackList,
          list: [],
          data: {
            trackId: 'id',
            trackCode: 'trackCode',
            trackName: 'trackName',
            lineList: 'lineList',
            siteId: 'siteId',
            directionId: 'directionId'
          },
          filterForm: {
            trackName: '',
            page: 1,
            size: 20
          },
          filterData: {
            trackName: {
              key: 'trackName',
              type: 'input',
              placeholder: '股道'
            }
          },
          columns: [
            { property: 'trackName', label: '股道' },
            { property: 'lineName', label: '线路', formatter: row => row.lineNameList ? row.lineNameList.map(item => item.lineName).join(',') : '' },
            { property: 'siteName', label: '区间站场' },
            { property: 'beginRoad', label: '起始公里标', formatter: row => this.formatRoad(row.beginRoad) },
            { property: 'endRoad', label: '结束公里标', formatter: row => this.formatRoad(row.endRoad) }
          ],
          total: 0
        },
        TUNNEL: {
          chooseType: 'selectTable',
          type: 'TUNNEL',
          key: 'tunnelName',
          name: '隧道',
          interface: tunnelList,
          list: [],
          data: {
            tunnelId: 'id',
            tunnelCode: 'tunnelCode',
            tunnelName: 'tunnelName',
            lineId: 'lineId',
            siteIds: 'siteIds',
            directionIds: 'directionIds'
          },
          filterForm: {
            tunnelName: '',
            page: 1,
            size: 20
          },
          filterData: {
            tunnelName: {
              key: 'tunnelName',
              type: 'input',
              placeholder: '隧道'
            }
          },
          columns: [
            { property: 'tunnelName', label: '隧道' },
            { property: 'lineName', label: '线路' },
            { property: 'siteName', label: '区间站场', formatter: row => row.siteNames ? row.siteNames.map(item => item.siteName).join('，') : '' },
            { property: 'beginRoad', label: '起始公里标', formatter: row => this.formatRoad(row.beginRoad) },
            { property: 'endRoad', label: '结束公里标', formatter: row => this.formatRoad(row.endRoad) }
          ],
          total: 0
        },
        ANCHOR: {
          chooseType: 'selectTable',
          type: 'ANCHOR',
          key: 'anchorNum',
          name: '锚段',
          interface: anchorList,
          list: [],
          data: {
            anchorId: 'id',
            anchorCode: 'anchorCode',
            anchorNum: 'anchorNum'
          },
          filterForm: {
            keyName: '',
            page: 1,
            size: 20
          },
          filterData: {
            keyName: {
              key: 'keyName',
              type: 'input',
              placeholder: '锚段编号、公里标'
            }
          },
          columns: [
            { property: 'lineName', label: '线路', formatter: row => row.lineAttr ? row.lineAttr.lineName : '' },
            { property: 'siteName', label: '区间站场', formatter: row => row.siteList ? row.siteList.map(item => item.siteName).join(',') : '' },
            { property: 'anchorNum', label: '锚段编号' },
            { property: 'pillar', label: '起止支柱号', formatter: row => `${row.beginPillarAttr && row.beginPillarAttr.pillarNum || ''} - ${row.endPillarAttr && row.endPillarAttr.pillarNum || ''}` }
          ],
          total: 0
        },
        PILLAR: {
          chooseType: 'selectTable',
          type: 'PILLAR',
          key: 'pillarNum',
          name: '支柱',
          interface: pillarList,
          list: [],
          data: {
            pillarId: 'id',
            pillarCode: 'pillarCode',
            pillarNum: 'pillarNum',
            roadMark: 'roadMark',
            anchorList: 'anchorList'
          },
          filterForm: {
            page: 1,
            size: 10,
            startPillar: '',
            endPillar: ''
          },
          filterData: {
            lineId: {
              key: 'lineId',
              type: 'selectTree',
              title: '线路',
              placeholder: '所有线路',
              options: [],
              props: {
                label: 'label',
                value: 'id',
                parent: 'parentId',
                children: 'children'
              },
              changeFn: (vm, node) => {
                this.$refs.selectTable.$refs.customSelect.focus()
                this.errorTypes.PILLAR.filterData['siteIds'].options = []
                this.$set(this.errorTypes.PILLAR.filterForm, 'siteIds', '')
                if (!node.id) return
                getListByLineId(node.id).then(response => {
                  this.errorTypes.PILLAR.filterData['siteIds'].options = response.data
                })
              },
              clearFn: () => {
                this.errorTypes.PILLAR.filterData['siteIds'].options = []
                this.$set(this.errorTypes.PILLAR.filterForm, 'siteIds', '')
              }
            },
            siteIds: {
              key: 'siteIds',
              type: 'select',
              title: '区间站场',
              placeholder: '所有区间站场',
              options: [],
              props: { label: 'siteName', value: 'id' },
              changeFn: (vm, node) => {
                this.$refs.selectTable.$refs.customSelect.focus()
              }
            },
            startPillar: {
              key: 'startPillar',
              type: 'input',
              placeholder: '开始支柱号'
            },
            endPillar: {
              key: 'endPillar',
              type: 'input',
              placeholder: '结束支柱号'
            }
          },
          columns: [
            { property: 'pillarNum', label: '支柱号' },
            { property: 'lineName', label: '线路', formatter: row => row.lineAttr ? row.lineAttr.lineName : '' },
            { property: 'siteName', label: '区间站场', formatter: row => row.siteAttr ? row.siteAttr.siteName : '' },
            { property: 'roadMark', label: '公里标', formatter: row => this.formatRoad(row.roadMark) }
          ],
          total: 0
        },
        JCW_DEVICE: {
          chooseType: 'selectTable',
          type: 'JCW_DEVICE',
          key: 'deviceName',
          name: '关键设备',
          interface: deviceList,
          list: [],
          data: {
            deviceId: 'id',
            deviceCode: 'deviceCode',
            deviceName: 'deviceName',
            devClassId: 'devClassAttr.devClassId',
            devClassCode: 'devClassAttr.devClassCode',
            devClassName: 'devClassAttr.devClassName'
          },
          filterForm: {
            keyName: '',
            page: 1,
            size: 20
          },
          filterData: {
            keyName: {
              key: 'keyName',
              type: 'input',
              placeholder: '设备名称、支柱号'
            }
          },
          columns: [
            { property: 'lineName', label: '线路', formatter: row => row.lineAttr ? row.lineAttr.lineName : '' },
            { property: 'siteName', label: '区间站场', formatter: row => row.siteAttr ? row.siteAttr.siteName : '' },
            { property: 'pillar', label: '支柱号', formatter: row => row.pillarList ? row.pillarList.map(item => item.pillarNum).join(',') : '' },
            { property: 'deviceName', label: '设备名称' }
          ],
          total: 0
        },
        DETECT_DEVICE: {
          chooseType: 'selectTable',
          type: 'DETECT_DEVICE',
          key: 'detectDeviceName',
          name: '检测设备',
          interface: device6cList,
          list: [],
          data: {
            detectDeviceId: 'id',
            detectDeviceCode: 'deviceCode',
            detectDeviceName: 'deviceName',
            cType: 'devClassId'
          },
          filterForm: {
            keyName: '',
            page: 1,
            size: 20
          },
          filterData: {
            keyName: {
              key: 'keyName',
              type: 'input',
              placeholder: '关键字查询'
            }
          },
          columns: [
            { property: 'deviceName', label: '设备名称' },
            { property: 'siteName', label: '区间站场', formatter: row => row.siteAttr ? row.siteAttr.siteName : '' },
            { property: 'pillar', label: '支柱号', formatter: row => row.pillarAttr ? row.pillarAttr.pillarNum : '' },
            { property: 'positionDesc', label: '安装位置描述' }
          ],
          total: 0
        },
        DEFECT_TYPE: {
          chooseType: 'selectTable',
          type: 'DEFECT_TYPE',
          key: 'userDefectTypeName',
          name: '缺陷分类',
          interface: userDefectTypeList,
          list: [],
          data: {
            userDefectTypeId: 'id',
            userDefectTypeCode: 'userDefectTypeCode',
            userDefectTypeName: 'userDefectTypeName',
            typeFullName: 'userDefectTypeName',
            idPath: 'idPath'
          },
          filterForm: {
            keyName: '',
            devClassId: '',
            page: 1,
            size: 20
          },
          filterData: {
            devClassId: {
              key: 'devClassId',
              type: 'selectTree',
              title: '设备分类',
              placeholder: '所有设备分类',
              options: [],
              props: {
                label: 'label',
                value: 'id',
                parent: 'parentId',
                children: 'children'
              },
              changeFn: _ => {
                this.$refs.selectTable.$refs.customSelect.focus()
              }
            },
            keyName: {
              key: 'keyName',
              type: 'input',
              placeholder: '请输入名称、编码'
            }
          },
          columns: [
            { property: 'userDefectTypeName', label: '缺陷分类名称' },
            { property: 'userDefectTypeDevClass', label: '设备分类', formatter: row => row.devClassAttr ? row.devClassAttr.devClassName : '' }
          ],
          total: 0
        },
        DEFECT_GRADE: {
          chooseType: 'selectTable',
          type: 'DEFECT_GRADE',
          key: 'userGradeName',
          name: '缺陷等级',
          interface: userDefectGradeList,
          list: [],
          data: {
            userGradeId: 'id',
            userGradeName: 'userGradeName',
            userSolveDays: 'userSolveDays',
            gradeId: 'gradeId'
          },
          filterForm: {
            keyName: '',
            page: 1,
            size: 20
          },
          filterData: {
            keyName: {
              key: 'keyName',
              type: 'input',
              placeholder: '请输入名称'
            }
          },
          columns: [
            { property: 'userGradeName', label: '缺陷等级名称' },
            { property: 'userSolveDays', label: '用户处理期限' }
          ],
          total: 0
        },
        JCW_REPAIR_RECORD_STATE: {
          chooseType: 'select',
          type: 'JCW_REPAIR_RECORD_STATE',
          name: '检修状态',
          list: [
            { label: '良好', value: 1 },
            { label: '有缺陷', value: 2 }
          ],
          data: null,
          rules: { type: 'number', required: true, message: '请选择', trigger: 'change' }
        }
      },
      defaultRules: { type: 'object', required: true, validator: (rule, value, callback) => {
        if (value && !isEmptyObject(value)) {
          callback()
        } else {
          callback(new Error('请选择'))
        }
      }, trigger: 'change' },
      defaultRules1: { required: true, message: '请输入', trigger: 'blur' },
      currentErrorType: {},
      selectData: [],
      dialog1: {
        title: '修前值',
        visible: false
      }
    }
  },
  computed: {
    viewJson() {
      return this.currentRow[0] && this.currentRow[0].original ? this.currentRow[0].original : {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.filterData.type.options = this.types
      getErrorType().then(response => {
        this.errorTypeList = response.data
        this.filterData.errorType.options = this.errorTypeList.map(item => ({
          label: item.name,
          value: item.type
        }))
        this.getListPage()
      })
      devClassList().then(response => {
        this.errorTypes.DEFECT_TYPE.filterData.devClassId.options = response.data
      })
      lineTreeList().then(response => {
        this.errorTypes.PILLAR.filterData['lineId'].options = response.data
      })
    },
    getListPage() {
      this.listLoading = true
      getListPage(this.listQuery)
        .then(response => {
          this.tableData = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
        .catch(_ => {
          this.listLoading = false
        })
    },
    chooseErrorType(type) {
      this.listQuery.errorType = type
      this.getListPage()
    },
    /** 主页搜索*/
    search() {
      this.listQuery.page = 1
      this.getListPage()
    },
    /** 操作查看 */
    view(row) {
      console.log('1111', row)
      this.currentRow = [row]
      console.log('2222', this.currentRow[0])
      const dialog = {
        title: '查看',
        visible: true,
        disabled: true,
        loading: false,
        form: row
      }
      this.dialog = Object.assign(this.dialog, dialog)
      this.getSelectData(this.dialog.form.errorType)
    },
    /** 主页添加 */
    addForm() {
      const dialog = {
        title: '添加',
        visible: true,
        disabled: false,
        loading: false,
        form: {
          status: 1,
          delFlag: 0,
          errorType: '',
          errorCode: '',
          type: 0,
          ruleList: [],
          data: {}}
      }
      this.dialog = Object.assign(this.dialog, dialog)
    },
    /** 操作编辑 */
    updateForm(row, index) {
      this.currentRow = [row]
      const dialog = {
        title: '编辑',
        visible: true,
        disabled: false,
        loading: false,
        form: JSON.parse(JSON.stringify(row))
      }
      this.dialog = Object.assign(this.dialog, dialog)
      this.getSelectData(this.dialog.form.errorType)
    },
    /** dialog添加或编辑接口 */
    updateData() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.dialog.loading = true
          updateData(this.dialog.form)
            .then(response => {
              this.dialog.visible = false
              this.dialog.loading = false
              this.currentRow = [response.data]
              if (this.dialog.title === '添加') {
                this.tableData.unshift(this.currentRow[0])
                this.total++
              } else {
                const index = this.tableData.findIndex(
                  item => item.id === this.currentRow[0].id
                )
                this.tableData.splice(index, 1, JSON.parse(JSON.stringify(this.currentRow[0])))
                this.$forceUpdate()
              }
              this.notifiySuccess('保存成功')
            })
            .catch(_ => {
              this.dialog.loading = false
            })
        }
      })
    },
    deleteData(row, index) {
      this.confirmBox('确定删除?')
        .then(() => {
          deleteData(row.id).then(response => {
            this.notifiySuccess('删除成功!')
            // this.tableData.splice(index, 1)
            // this.total--
            this.getListPage()
          })
        })
        .catch(() => {})
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    beforeCloseDialog() {
      this.selectData = []
      this.currentErrorType = {}
    },
    // 改变规则类型
    changeType(val) {
      this.changeErrorType(this.dialog.form.errorType)
    },
    // 改变预处理类型
    changeErrorType(val) {
      const type = val
      this.currentErrorType = {}
      if (this.dialog.form.type === 2) {
        // 替换
        this.dialog.form.data = ''
        this.dialog.form.errorCode = ''
      } else if (this.dialog.form.type === 1) {
        // 别名
        this.dialog.form.data = type && this.errorTypes[type].data ? {} : null
        this.dialog.form.errorCode = ''
      } else if (this.dialog.form.type === 0) {
        // 编码预处理
        this.dialog.form.data = type && this.errorTypes[type].data ? {} : null
        this.dialog.form.ruleList = []
      }
      if ((this.dialog.form.type === 0 || this.dialog.form.type === 1) && !isEmptyObject(this.currentErrorType) && this.currentErrorType.list.length) return
      if (!type || this.dialog.form.type === 2) return
      this.$nextTick(_ => {
        this.getSelectData(type)
      })
    },
    getSelectData(type) {
      this.selectData = []
      this.currentErrorType = this.errorTypes[type]
      if (this.currentErrorType.list.length) {
        this.selectData = this.currentErrorType.list
        return
      }
      if (type === 'DEPT') {
        this.currentErrorType.interface().then(response => {
          this.selectData = response.data
          this.currentErrorType.list = response.data
        })
      } else {
        this.currentErrorType.interface({ page: 1, size: 10 }).then(response => {
          this.selectData = response.data.records
          this.currentErrorType.list = response.data.records
          this.currentErrorType.total = response.data.total
        })
      }
    },
    // 部门 的预处理类型 选择
    changeDept(vm, node) {
      this.$set(this.dialog.form, 'data', {
        deptId: node.id,
        deptCode: node.obj.deptCode,
        deptName: node.label,
        parentCode: node.obj.parentCode
      })
    },
    clearDept() {
      this.dialog.form.data = {}
    },
    // 检修类型 的预处理类型 选择
    changeSelect(val) {
      this.dialog.form.data = val
    },
    // 下拉表格 的预处理类型 选择
    changeData(data) {
      this.parseData(data)
    },
    parseData(data) {
      const result = {}
      Object.keys(this.currentErrorType.data).forEach(item => {
        const key = this.currentErrorType.data[item]
        result[item] = this.parseKey(key, data)
      })
      this.dialog.form.data = result
    },
    parseKey(key, data) {
      if (key.includes('.')) {
        const keys = key.split('.')
        let data1 = JSON.parse(JSON.stringify(data))
        for (let i = 0; i < keys.length; i++) {
          if (typeof data1[keys[i]] === 'object' && data1[keys[i]] !== null) {
            data1 = data1[keys[i]]
          } else {
            return data1[keys[i]]
          }
        }
      } else {
        return data[key]
      }
    },
    handleCloseRule(index) {
      this.dialog.form.ruleList.splice(index, 1)
    },
    handleRuleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dialog.form.ruleList.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    showRuleInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.ruleInput.$refs.input.focus()
      })
    },
    showJson(row) {
      this.currentRow = [row]
      this.dialog1.visible = true
    }
  }
}
</script>

<style lang="scss">
  .pretreatment-rule-dialog, .pretreatment-rule-dialog1{
    .el-dialog{
      .el-dialog__body{
        height: calc(100vh - 70px);
      }
    }
  }
  .el-tag {
    margin-right: 10px;
  }
  .rule-tag-input{
    width: 90px;
    vertical-align: bottom;
  }
  .rule-tag-button{
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
